<template>
  <div class="auth-container">
    <div class="auth-card">
      <div class="auth-header">
        <h2>用户注册</h2>
        <p>创建您的账号</p>
      </div>

      <div class="auth-form">
        <div class="form-item">
          <el-input
            v-model="registerForm.username"
            placeholder="请输入用户名"
            size="large"
            :prefix-icon="User"
            @blur="validateUsername"
          />
        </div>

        <div class="form-item">
          <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="请输入密码"
            size="large"
            :prefix-icon="Lock"
            show-password
            @blur="validatePassword"
          />
        </div>

        <div class="form-item">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="请确认密码"
            size="large"
            :prefix-icon="Lock"
            show-password
            @blur="validateConfirmPassword"
          />
        </div>

        <el-button
          type="primary"
          size="large"
          class="submit-btn"
          :loading="loading"
          @click="handleRegister"
        >
          {{ loading ? '注册中...' : '立即注册' }}
        </el-button>

        <div class="auth-switch">
          已有账号？
          <span class="switch-link" @click="goToLogin">立即登录</span>
        </div>
      </div>
    </div>

    <!-- 加载遮罩 -->
    <div v-if="loading" class="loading-overlay">
      <el-icon class="is-loading" color="#409eff" :size="32">
        <Loading />
      </el-icon>
    </div>

    <!-- 消息提示容器 -->
    <div class="message-box"></div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock, Loading } from '@element-plus/icons-vue'
import { useUserStore } from '../stores/user.js'

const router = useRouter()
const userStore = useUserStore()
const loading = ref(false)

// 注册表单数据
const registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: ''
})

// 检查用户名是否已存在
const checkUsernameExists = async (username) => {
  if (!username.trim()) return ''
  
  const checkResult = await userStore.checkFieldExists('username', username)
  
  if (checkResult.exists) {
    return '用户名已存在'
  }
  
  return ''
}

// 验证用户名
const validateUsername = () => {
  if (!registerForm.username.trim()) {
    return '用户名不能为空'
  }
  if (registerForm.username.length < 3) {
    return '用户名长度不能少于3位'
  }
  if (!/^[a-zA-Z0-9_]+$/.test(registerForm.username)) {
    return '用户名只能包含字母、数字和下划线'
  }
  return ''
}

// 验证密码
const validatePassword = () => {
  if (!registerForm.password) {
    return '密码不能为空'
  }
  if (registerForm.password.length < 6) {
    return '密码长度不能少于6位'
  }
  return ''
}

// 验证确认密码
const validateConfirmPassword = () => {
  if (!registerForm.confirmPassword) {
    return '请确认密码'
  }
  if (registerForm.confirmPassword !== registerForm.password) {
    return '两次输入的密码不一致'
  }
  return ''
}

// 表单验证
const validateForm = () => {
  const errors = []
  
  const usernameError = validateUsername()
  if (usernameError) errors.push(usernameError)
  
  const passwordError = validatePassword()
  if (passwordError) errors.push(passwordError)
  
  const confirmPasswordError = validateConfirmPassword()
  if (confirmPasswordError) errors.push(confirmPasswordError)
  
  return errors
}

// 处理注册
const handleRegister = async () => {
  const errors = validateForm()
  
  if (errors.length > 0) {
    ElMessage.error(errors[0])
    return
  }

  loading.value = true

  try {
    // 检查用户名是否已存在
    const usernameCheck = await checkUsernameExists(registerForm.username)
    
    if (usernameCheck) {
      ElMessage.error(usernameCheck)
      return
    }

    // 使用用户状态管理注册
    const result = await userStore.register({
      username: registerForm.username,
      password: registerForm.password
    })
    
    if (result.success) {
      ElMessage.success('注册成功！')
      
      // 跳转到登录页面
      setTimeout(() => {
        router.push('/login')
      }, 1500)
    } else {
      ElMessage.error(result.error || '注册失败')
    }
  } catch (error) {
    console.error('注册异常:', error)
    ElMessage.error('注册失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 跳转到登录页面
const goToLogin = () => {
  router.push('/login')
}
</script>

<style scoped lang="scss">
// 导入全局样式
@use '../assets/styles/main.scss';

// 注册页面特定样式
.auth-container {
  .auth-card {
    max-width: 450px;

    .auth-header {
      h2 {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
      }
    }
  }
}
</style>
